package com.szqhyxj.youxiangju.biz.card.addCard;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.szqhyxj.youxiangju.BaseActivity;
import com.szqhyxj.youxiangju.R;
import com.szqhyxj.youxiangju.biz.card.CardActivity;
import com.szqhyxj.youxiangju.biz.core.PhotoBridge;
import com.szqhyxj.youxiangju.biz.core.UserInfoManger;
import com.szqhyxj.youxiangju.sys.components.LoadImageUtils;
import com.szqhyxj.youxiangju.sys.components.NavigationBar;
import com.szqhyxj.youxiangju.sys.components.androidpicker.qqtheme.framework.picker.OptionPicker;
import com.szqhyxj.youxiangju.sys.components.androidpicker.qqtheme.framework.util.PickerUtil;
import com.szqhyxj.youxiangju.sys.components.view.popview.HintPopView;
import com.szqhyxj.youxiangju.sys.components.view.popview.SingleDialog;
import com.szqhyxj.youxiangju.sys.util.FileUtils;
import com.szqhyxj.youxiangju.sys.util.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CustomAdapt;

public class BindCardActivity extends BaseActivity implements BinCardContarct.View, NavigationBar.NavigationBarListener ,CustomAdapt{

    @BindView(R.id.navigationBar)
    NavigationBar navigationBar;
    @BindView(R.id.photograph)
    ImageView photograph;
    @BindView(R.id.txt_Photograph)
    TextView txtPhotograph;
    @BindView(R.id.cardholder)
    TextView cardholder;
    @BindView(R.id.card_no)
    EditText cardNo;
    @BindView(R.id.issuing_bank)
    TextView issuingBank;
    @BindView(R.id.input_period_of_validity)
    EditText inputPeriodOfValidity;
    @BindView(R.id.period_of_validity)
    ImageView periodOfValidity;
    @BindView(R.id.input_CVN2)
    EditText inputCVN2;
    @BindView(R.id.cvn2)
    ImageView cvn2;
    @BindView(R.id.accountant_bill_date)
    TextView accountantBillDate;
    @BindView(R.id.due_date)
    TextView dueDate;
    @BindView(R.id.fixed_quota)
    EditText fixedQuota;
    @BindView(R.id.phone_code)
    EditText phoneCode;
    @BindView(R.id.auth_code)
    EditText authCode;
    @BindView(R.id.acquire)
    TextView acquire;
    @BindView(R.id.present)
    Button present;
    @BindView(R.id.due_date_line)
    LinearLayout dueDateLine;
    @BindView(R.id.yuan)
    TextView yuan;
    private BindCardPresenter presenter;
    private static final int REQUEST_TAKE_PHOTO = 1;
    private static final int REQUEST_GALLERY = 3;

    private boolean isGain = true;
    private int time = 60;
    private String mTimer;
    private Timer timer;
    private TimerTask task;
    private String phone;
    private File pictureFile;

    public static void start(Activity activity) {
        Intent intent = new Intent();
        intent.setClass(activity, BindCardActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public boolean isBaseOnWidth(){
        return true;
    }

    @Override
    public float getSizeInDp(){
        return 360;
    }

    private static abstract class SimpleTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 如果返回值是正常的话

        if (resultCode == Activity.RESULT_OK) {
            // 验证请求码是否一至，也就是startActivityForResult的第二个参数
            switch (requestCode) {
                case REQUEST_TAKE_PHOTO:
                    //   String file = data.getStringExtra(CameraUtils.TEMPFILE);
                   sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(pictureFile.getAbsolutePath())));
//                    //加载图片
//                    LoadImageUtils.loadImage(photograph, tempFile);
                 //   presenter.ocrPhotograph(pictureFile);
                    presenter.setTempFile(pictureFile);
                    showPhotograph(pictureFile);
                    break;
                case REQUEST_GALLERY:
                    Uri uri = data.getData();
                    File tempFile = FileUtils.uri2File(BindCardActivity.this, uri);
                 //   presenter.ocrPhotograph(tempFile);
                    presenter.setTempFile(tempFile);
                    showPhotograph(tempFile);
                    break;
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_card);
        ButterKnife.bind(this);
        presenter = new BindCardPresenter(this);
        navigationBar.setNavigationBarListener(this);
        initEvents();
    }


    private void initEvents() {
        cardholder.setText(UserInfoManger.INSTANCE.getUser().getUsername());
        presenter.setUsername(UserInfoManger.INSTANCE.getUser().getUsername());


        cardNo.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                presenter.setBankCardNo(charSequence.toString());
            }
        });

        inputCVN2.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                presenter.setCvn(charSequence.toString());
            }
        });

        fixedQuota.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                presenter.setFixedAmount(charSequence.toString());
                if(i == 0){
                    yuan.setVisibility(View.INVISIBLE);
                }else {
                    yuan.setVisibility(View.VISIBLE);
                }
            }
        });

        phoneCode.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                presenter.setCardPhone(charSequence.toString());
            }
        });

        authCode.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                presenter.setSendValidCode(charSequence.toString());
            }
        });

        inputPeriodOfValidity.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                presenter.setExpiryDate(charSequence.toString());
            }
        });
    }


    @OnClick({R.id.issuing_bank_line, R.id.accountant_bill_date_line, R.id.due_date_line
            , R.id.present, R.id.cvn2, R.id.acquire, R.id.period_of_validity, R.id.photograph, R.id.txt_Photograph})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.issuing_bank_line:
                presenter.getIssuingBank();
                break;
            case R.id.accountant_bill_date_line:
                PickerUtil.onDayPicker(this, new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                        accountantBillDate.setText(item);
                        presenter.setAccountantBillDate(item.replace("日",""));
                    }
                });
                break;
            case R.id.due_date_line:
                PickerUtil.onDayPicker(this, new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                        dueDate.setText(item);
                        presenter.setDueDate(item.replace("日",""));
                    }
                });
                break;
            case R.id.acquire:
                presenter.getPhoneCode();
                break;
            case R.id.present:
                presenter.present();
                break;
            case R.id.cvn2:
                HintPopView cvnPopView = new HintPopView(this, getResources().getString(R.string.card_cvn2), R.mipmap.cvn2);
                cvnPopView.show();
                break;
            case R.id.period_of_validity:
                HintPopView hintPopView = new HintPopView(this, getResources().getString(R.string.credit_period_of_validity), R.mipmap.youxiaoqi);
                hintPopView.show();
                break;
            case R.id.photograph:
            case R.id.txt_Photograph:
                final SingleDialog singleDialog = new SingleDialog(BindCardActivity.this);
                singleDialog.setISharePlatformListener(new SingleDialog.ISharePlatformListener() {
                    @Override
                    public void sharePlatform(String platform) {

                    }

                    @Override
                    public void onClickAlbum(View view) {
                        presenter.selectFromGalleryFor();
                        singleDialog.dismiss();
                    }

                    @Override
                    public void onTakePhoto(View view) {
                        try {
                            presenter.takePhotoFor(BindCardActivity.this);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        singleDialog.dismiss();
                    }
                });
                singleDialog.show();

                break;
        }
    }

    @Override
    public void navigationLeft() {
        CardActivity.start(this);
    }

    @Override
    public void navigationRight() {

    }

    @Override
    public void showIssuingBank(String[] issuingBanks) {

        PickerUtil.onOptionPicker(this, issuingBanks, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                BindCardActivity.this.issuingBank.setText(item);
                presenter.setIssuingBank(index);
            }
        });

    }

    @Override
    public void showCardNo(String cardNo) {
        this.cardNo.setText(cardNo);
    }

    @Override
    public void showDueDate(String dueDate) {
       // this.dueDate.setText(dueDate);
    }

    @Override
    public void showAccountantBillDate(String accountantBillDate) {
       // this.accountantBillDate.setText(accountantBillDate);
    }

    @Override
    public void showPhotograph(File file) {
        LoadImageUtils.loadImageRotation(photograph, file,270);
    }

    @Override
    public void showPhoneCode() {

        phone = phoneCode.getText().toString();
        if (TextUtils.isEmpty(phone) || phone.length() < 11) {
            ToastUtils.showTost(this, "请输入正确手机号");
            return;
        }

        if (isGain) {
            isGain = false;
            timer = new Timer();

            task = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            time--;
                            mTimer = time + "S";

                            if (time <= 0) {
                                isGain = true;
                                mTimer = "获取";
                                timer.cancel();
                                time = 60;
                            }

                            acquire.setText(mTimer);
                        }
                    });
                }
            };

            timer.schedule(task, time, 1000);
            presenter.bankCreditCard();
        }

    }

    @Override
    public void navToGalleryFor() {
        PhotoBridge.startToGallery(this, REQUEST_GALLERY);
    }

    @Override
    public void navToTakePhoto(File file) {
        pictureFile = file;
        PhotoBridge.startToTakePicture(this, REQUEST_TAKE_PHOTO, file);
    }

    @Override
    public void navErr(String err) {
        BindCardErrActivity.start(this, err);
    }

    @Override
    public void navSuccess(String success) {
        BinCardSucceedActivity.start(this, "");
    }

    @Override
    public void previewFace(File file) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            CardActivity.start(this);
        }
        return super.onKeyDown(keyCode, event);
    }

}
